import plugin from '../../lib/plugins/plugin.js'
import { XiuXianData } from './xiuxian_data.js'
import { XiuXianUtils } from './xiuxian_utils.js'

export class XiuXianItems extends plugin {
    constructor() {
        super({
            name: '修仙文游物品',
            dsc: '修仙游戏的物品相关功能',
            event: 'message',
            priority: 5000,
            rule: [
                { reg: '^商店$', fnc: 'showShop' },
                { reg: '^购买(.*)$', fnc: 'buyItem' },
                { reg: '^使用(.*)$', fnc: 'useItem' }
            ]
        })
        this.data = new XiuXianData()
        this.utils = new XiuXianUtils()
    }

    async showShop(e) {
        const userId = e.user_id
        const player = this.data.gameState[userId]
        if (!player) return this.reply('请先输入"修仙"开始游戏')

        const shopList = this.data.shop.map(item => {
            let effectDescription = ''
            if (item.effect.type === 'energy') {
                effectDescription = `恢复${item.effect.value}点灵力`
            } else if (item.effect.type === 'exp') {
                effectDescription = `增加${item.effect.value}点经验`
            } else if (item.effect.type === 'attribute') {
                if (item.effect.attribute === 'all') {
                    effectDescription = `永久提升所有属性${item.effect.value}点`
                } else {
                    effectDescription = `永久提升${item.effect.attribute}${item.effect.value}点`
                }
            } else if (item.effect.type === 'heal') {
                effectDescription = `立即恢复${item.effect.value}点生命值`
            } else if (item.effect.type === 'special') {
                effectDescription = `特殊效果：${item.effect.value}`
            } else if (item.effect.type === 'buff') {
                effectDescription = `临时提升${item.effect.attribute}${item.effect.value}点，持续${item.effect.duration}次战斗`
            }
            return `${item.name} - ${item.price}灵石
效果: ${effectDescription}
描述: ${item.description || '无描述'}
-----------------`
        }).join('\n')

        const avatarUrl = `![图片 #20px #20px](https://q1.qlogo.cn/g?b=qq&s=0&nk=${e.user_id})`;

        const shopText = `${avatarUrl}修仙商店
***
# 商品列表
\`\`\`
${shopList}
\`\`\`

使用"购买+物品名"来购买物品
点击展开向下滑动查看更多
当前灵石: ${player.lingshi}
    `.trim()

        const forwardMsg = await this.utils.markdown(e, shopText, '修仙商店')
        return this.reply(forwardMsg)
    }

    async buyItem(e) {
        const userId = e.user_id
        const player = this.data.gameState[userId]
        if (!player) return this.reply('请先输入"修仙"开始游戏')

        const itemName = e.msg.replace(/^购买/, '').trim()
        const item = this.data.shop.find(i => i.name === itemName)

        if (!item) return this.reply('商店中没有这个物品')
        if (player.lingshi < item.price) return this.reply('灵石不足，无法购买')

        player.lingshi -= item.price
        this.utils.addItemToInventory(player, item.name)
        this.utils.saveJSON(this.data.paths.gameData, this.data.gameState)

        return this.reply(`成功购买${item.name}，消耗${item.price}灵石`)
    }

    async useItem(e) {
        const userId = e.user_id
        const player = this.data.gameState[userId]
        if (!player) return this.reply('请先输入"修仙"开始游戏')

        const itemName = e.msg.replace(/^使用/, '').trim()
        let category = Object.keys(player.inventory).find(cat => player.inventory[cat].includes(itemName))

        if (!category) return this.reply('你没有这个物品')

        const itemIndex = player.inventory[category].indexOf(itemName)
        player.inventory[category].splice(itemIndex, 1)

        const item = this.data.shop.find(i => i.name === itemName)
        if (item) {
            if (item.effect.type === 'energy') {
                player.energy = Math.min(player.energy + item.effect.value, 100)
                this.utils.saveJSON(this.data.paths.gameData, this.data.gameState)
                return this.reply(`使用${itemName}恢复了${item.effect.value}点灵力，当前灵力：${player.energy}`)
            } else if (item.effect.type === 'exp') {
                player.exp += item.effect.value
                this.utils.saveJSON(this.data.paths.gameData, this.data.gameState)
                return this.reply(`使用${itemName}获得了${item.effect.value}点经验，当前经验：${player.exp}`)
            } else if (item.effect.type === 'attribute') {
                if (item.effect.attribute === 'all') {
                    ['attack', 'defense', 'speed', 'maxHp', 'magicAttack', 'magicDefense'].forEach(attr => {
                        player[attr] += item.effect.value
                    })
                } else {
                    player[item.effect.attribute] += item.effect.value
                }
                this.utils.saveJSON(this.data.paths.gameData, this.data.gameState)
                return this.reply(`使用${itemName}永久提升了属性`)
            } else if (item.effect.type === 'heal') {
                const healAmount = Math.min(item.effect.value, player.maxHp - player.hp)
                player.hp += healAmount
                this.utils.saveJSON(this.data.paths.gameData, this.data.gameState)
                return this.reply(`使用${itemName}恢复了${healAmount}点生命值，当前生命值：${player.hp}`)
            } else if (item.effect.type === 'buff') {
                if (!player.battleBuffs) player.battleBuffs = []
                player.battleBuffs.push({
                    attribute: item.effect.attribute,
                    value: item.effect.value,
                    duration: item.effect.duration
                })
                this.utils.saveJSON(this.data.paths.gameData, this.data.gameState)
                return this.reply(`使用${itemName}获得了临时增益效果，持续${item.effect.duration}次战斗`)
            }
        }

        this.utils.saveJSON(this.data.paths.gameData, this.data.gameState)
        return this.reply(`使用了${itemName}，但似乎没有什么特殊效果`)
    }
}
